<template>
  <div class="demo-split">
    <Split v-model="split2" mode="vertical">
      <div slot="top" class="demo-split-pane" style="margin: 20px">
        <Form ref="formInline"  inline label-position="left">

          <FormItem>
            <Select v-model="selectValue" style="width:200px">
              <Option v-for="item in selectList" :value="item.value" :key="item.value">{{ item.label }}</Option>
            </Select>
          </FormItem>
          <FormItem>
            <Input type="text" v-model="buildVersion" placeholder="">
              <span slot="prepend">导入版本号</span>
            </Input>
          </FormItem>
          <FormItem>
            <!--headers="{'Content-Type': 'multipart/form-data'}"-->
            <Upload :max-size="1048576"
                    ref="upload"
                    :action="uploadUrl"
                    name="file"

                    :show-upload-list="true"
                    :on-format-error="handleFormatError"
                    :before-upload="beforeHandler"
                    :on-success="handleSuccess"
                    :on-preview="handleReturn"
                    :on-error="handleError"
                    :format="['xlsx','xls']"
                    :data="extraData">
              <Button type="info" icon="ios-cloud-upload-outline">导入</Button>
            </Upload>
          </FormItem>
        </Form>

      </div>

      <div slot="bottom" class="demo-split-pane">
        <Table v-if="selectValue==5" :columns="tableColumns2" :data="tableData2"></Table>
        <Table v-else :columns="tableColumns2" :data="tableData2"></Table>
        <br>
        <div id="myChart" :style="{width: '80%', height: '200px'}"></div>

       <Modal width="90%"
               title="详情"
               v-model="detailModal"
              @on-ok="detailModalOk"
              @on-cancel="detailModalCancel"
               :mask-closable="false">
          <Table  border :columns="detailColumns" :data="detailData" height="400">
          </Table>
        </Modal>

        <Modal width="75%"
               title="车牌号重复"
               @on-ok="modalOk"
               @on-cancel="modalCancel"
               v-model="modalTable"
               :mask-closable="false">

          <!-- <Table border :columns="columns1Right1" :data="data1"  height="400">
             &lt;!&ndash;<div slot="header"><strong>同牌异名-导入数据</strong></div>&ndash;&gt;
           </Table>-->

          <Table v-if="selectValue==5" border :columns="columns2Right1" :data="data1" height="400">
            <!--<div slot="header"><strong>同牌异名-导入数据</strong></div>-->
          </Table>
          <Table v-else border :columns="columns1Right1" :data="data1" height="400">
            <!--<div slot="header"><strong>同牌异名-导入数据</strong></div>-->
          </Table>
        </Modal>

        <Modal width="75%"
               title="存在重复数据"
               v-model="modalTableRepeat"
               :mask-closable="false">

          <Table v-if="selectValue==5" border :columns="columns2Right1" :data="dataRepeat2" height="400">
            <!--<div slot="header"><strong>同牌异名-导入数据</strong></div>-->
          </Table>
          <Table v-else border :columns="columns1Right1" :data="dataRepeat1" height="400">
            <!--<div slot="header"><strong>同牌异名-导入数据</strong></div>-->
          </Table>

          <div slot="footer">
            <Button type="info" @click="closeRepeat">确认</Button>
          </div>
        </Modal>
      </div>
    </Split>
  </div>
</template>

<script>
  import {baseUrl} from "../../api/api";
  import {req} from "../../api/axiosFun";
  import {websocketUrl} from "../../api/api";
  import {columns2Right1} from './addInfoConst'
  import {columns1Right1} from "./addInfoConst";
  import {detailColumns} from "./addInfoConst"

  export default {
    name: "AddInfo",
    mounted() {
      this.user = JSON.parse(localStorage.getItem('userdata'))
      this.initWebSocket();
      // this.uuid=this.getUuid();
      req('post', baseUrl + '/company/list')
        .then(res => {
          let data = res.data
          for (let e of data) {
            if (e.children == null) {
              delete e.children
            } else {
              for (let i of e.children) {
                if (i.children == null) {
                  delete i.children
                }
              }
            }
          }
          this.$store.commit('setCompanyInfo', data)
        });
    },
    computed: {
      companyInfo() {
        return this.$store.state.companyInfo
      }
      /* data1() {
         return this.$store.state.addReturn.resMap.newList
       },
       data2() {
         return this.$store.state.addReturn.resMap.oldList
       }*/
    },

    data() {
      return {
        detailModal: false,
        detailColumns: detailColumns,
        detailData: [],
        buildVersion: "",
        companyInfoValue: [],
        modalTableRepeat: false,
        dataRepeat1: [],
        dataRepeat2: [],

        data1: [],
        columns1Right1: columns1Right1,
        columns2Right1: columns2Right1,
        tableData2: [],
        tableData1: [],
        tableColumns2: [
          {
            key: 'total',
            title: '上次导入条数'
          }, {
            key: 'totalCurrent',
            title: '本次导入条数'
          },
          {
            key: 'dealTotal',
            title: '上次导入已批条数'
          }, {
            key: 'dealTotalCurrent',
            title: '本次导入已批条数'
          }, {
            key: 'cancelTotal',
            title: '上次导入取消条数'
          }, {
            key: 'cancelTotalCurrent',
            title: '本次导入取消条数'
          }, {
            key: 'newTotal',
            title: '上次导入新增条数'
          }, {
            key: 'newTotalCurrent',
            title: '本次导入新增条数'
          }, {
            key: 'buildVersion',
            title: '本次导入版本号'
          }, {
            key: 'selectType',
            title: '导入类型',
            render: (h, params) => {

              let status = params.row.selectType; //0:空闲  1:游戏  2:未上线
              if (status === 1) {
                return h('div', {props:{}},'养护生产-路网')
              }
              if (status === 2) {
                return h('div',  {props:{}},'生产生活-路网')
              }
              if (status ===3) {
                return h('div', {props:{}}, '养护生产-区间')
              }
              if (status ===4) {
                return h('div',  {props:{}},'生产生活-区间')
              }
              if (status ===5) {
                return h('div', {props:{}}, '员工通勤-区间')
              }
            }
          }, {
            title: '操作',
            key: 'action',
            width: 150,
            align: 'center',
            render: (h, params) => {
              return h('div', [
                h('Button', {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  style: {
                    marginRight: '5px'
                  },
                  on: {
                    click: () => {
                      let oldVersion = params.row.oldVersion
                      let newVersion =  params.row.buildVersion
                      this.showImportDetail(oldVersion, newVersion);
                    }
                  }
                }, '查看'),
                h('Button', {
                  props: {
                    type: 'error',
                    size: 'small'
                  },
                  on: {
                    click: () => {
                      this.deleteByVersion(params.row.buildVersion, params.row.selectType,params.index)
                    }
                  }
                }, '删除')
              ]);
            }
          }
        ],
        tableColumns1: [],
        modalTableColumns: [],
        modalTable: false,
        extraData: {
          data: this.selectValue,
          uuid: this.uuid,
          companyId: this.companyInfoValue,
          buildVersion: this.buildVersion
        },
        uploadUrl: baseUrl + '/upload/upload',
        selectValue: 1,
        selectList: [
          {
            label: '养护生产-路网',
            value: 1
          }, {
            label: '生产生活-路网',
            value: 2
          }, {
            label: '养护生产-区间',
            value: 3
          }, {
            label: '生产生活-区间',
            value: 4
          }, {
            label: '员工通勤-区间',
            value: 5
          }
        ],
        split2: 0.4,
        uesr: {},
        ws: {},
        uuid: this.getUuid()
      }
    },
    methods: {

      detailModalOk() {
        this.detailModal = false;
      },
      detailModalCancel() {
        this.detailModal = false;
      },
      showImportDetail(oldVersion, newVersion) {

        this.$axios.get(baseUrl + "/upload/compareVersions", {params :{oldVersion: oldVersion, newVersion: newVersion}})
          .then(res => {
            this.detailData = res.data.data;
            this.detailModal = true;
          })
      },
      deleteByVersion(buildVersion, selectType,index) {
        const delUrl = baseUrl + "/employFreeApply/delete"
        let data = {"buildVersion":buildVersion,"selectType":selectType};
        this.$axios.delete(delUrl, {data:data}).then(res => {
        this.tableData2.splice(index,1);
        })
      },
      closeRepeat() {
        this.modalTableRepeat = false
      },
      randomNum(n) {
        var rnd = "";
        for (var i = 0; i < n; i++)
          rnd += Math.floor(Math.random() * 10);
        return rnd;
      },
      modalCancel() {
        this.ws.send("cancel");
        this.modalTable = false
      },
      modalOk() {
        this.ws.send("ok");
        this.modalTable = false
      },
      getUuid() {
        var s = [];
        var hexDigits = "0123456789abcdef";
        for (var i = 0; i < 36; i++) {
          s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
        }
        s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
        s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
        s[8] = s[13] = s[18] = s[23] = "-";
        String.prototype.replaceAllStr = function (oldStr, newStr) {//吧f替换成e
          var reg = new RegExp(oldStr, "g"); //创建正则RegExp对象
          return this.replace(reg, newStr);
        };
        var uuid = s.join("").replaceAllStr("-", "");
        return uuid.toString();
      },
      onclose(e) {
        console.log("连接中断");
      },
      onopen(e) {
        console.log("连接成功");
      },
      onmessage(evt) {
        let that = this;
        let data = JSON.parse(evt.data);
        if (data.isRepeat == "540") {
          that.data1 = data.reList
          that.modalTable = true;
        }
      },
      initWebSocket() { //初始化weosocket  this.user.username+this.randomNum()
        if ('WebSocket' in window) {
          this.ws = new WebSocket(websocketUrl + this.uuid);
        } else if ('MozWebSocket' in window) {
          this.ws = new MozWebSocket(websocketUrl + this.uuid);
        } else {
          this.$Notice.warning({
            title: '浏览器版本过低',
            desc: '请升级浏览器'
          })
        }
        this.ws.onmessage = this.onmessage;

        this.ws.onclose = this.onclose;

        this.ws.onopen = this.onopen

      },

      beforeHandler(file) {

        if (this.buildVersion == null || this.buildVersion == '') {
          this.$Modal.info({
            title: "请输入版本号",
            content: "请输入版本号"
          });
          return false
        }
        this.extraData.data = this.selectValue;
        this.extraData.uuid = this.uuid
        this.extraData.companyId = this.companyInfoValue
        this.extraData.buildVersion = this.buildVersion

      },
      handleReturn(file) {
      },
      handleFormatError(file) {
        this.$Notice.warning({
          title: '文件格式不正确',
          desc: '文件 ' + file.name + ' 格式不正确，请上传.xls,.xlsx文件。'
        })
      },
      handleSuccess(res, file) {
        if (this.selectValue === 5) {
          if (res.data.code == 530) {
            this.modalTableRepeat = true
            this.dataRepeat2 = res.data.data.reList
            this.$Message.error("excel中有重复数据！")
            this.$refs.upload.clearFiles()
            return;
          }
          if (res.data.code == 550) {
            this.$Modal.info({
              title: "申请单位不在申请公司范围内",
              content: "申请单位不在申请公司范围内"
            });
            this.$Message.error("excel中有重复数据！")
            this.$refs.upload.clearFiles()
            return
          }
          if (res.data.code == 510) {
            this.$Modal.info({
              title: "导入版本号已经存在",
              content: "导入版本号已经存在"
            });
            this.$Message.error("导入版本号已经存在！")
            this.$refs.upload.clearFiles()
            return
          }
          this.tableData2 = res.data.data.cllectInfo;
        }
        if (this.selectValue !== 5) {
          if (res.data.code == 530) {
            this.modalTableRepeat = true
            this.dataRepeat1 = res.data.data.reList
            this.$Message.error("excel中有重复数据！")
            this.$refs.upload.clearFiles()
            return
          }
          if (res.data.code == 550) {
            this.$Modal.info({
              title: "申请单位不在申请公司范围内",
              content: "申请单位不在申请公司范围内"
            });
            this.$Message.error("excel中有重复数据！")
            this.$refs.upload.clearFiles()
            return
          }
          if (res.data.code == 510) {
            this.$Modal.info({
              title: "导入版本号已经存在",
              content: "导入版本号已经存在"
            });
            this.$Message.error("导入版本号已经存在！")
            this.$refs.upload.clearFiles()
            return
          }
          this.tableData2 = res.data.data.cllectInfo;
        }
        this.drawChart(res.data.data.cllectInfo)
        this.$Message.success("数据导入成功！")
        this.$refs.upload.clearFiles()
      },
      handleError(error, file) {
        this.$Message.error("数据导入失败！")
      },
      clone(obj) {
        let temp = null;
        if (obj instanceof Array) {
          temp = obj.concat();
        } else if (obj instanceof Function) {
          //函数是共享的是无所谓的，js也没有什么办法可以在定义后再修改函数内容
          temp = obj;
        } else {
          temp = new Object();
          for (let item in obj) {
            let val = obj[item];
            temp[item] = typeof val == 'object' ? clone(val) : val; //这里也没有判断是否为函数，因为对于函数，我们将它和一般值一样处理
          }
        }
        return temp;
      },
      drawChart(data) {
        // let yData = [data[0].total,
        //   data[0].totalCurrent,
        //   data[0].dealTotal,
        //   data[0].dealTotalCurrent,
        //   data[0].cancelTotal,
        //   data[0].cancelTotalCurrent,
        //   data[0].newTotal,
        //   data[0].newTotalCurrent]
        // 基于准备好的dom，初始化echarts实例
        let myChart = this.$echarts.init(document.getElementById('myChart'))
        // 绘制图表
        myChart.setOption({
          // title: {text: '在Vue中使用echarts'},
          tooltip: {},
          legend: {
            data: ['导入条数', '已批条数', '取消条数', '新增条数']
          },
          xAxis: {
            data: ["上次", "本次"]
          },
          yAxis: {},
          series: [{
            name: '导入条数',
            type: 'bar',
            data: [data[0].total,
              data[0].totalCurrent]
          }, {
            name: '已批条数',
            type: 'bar',
            data: [data[0].dealTotal,
              data[0].dealTotalCurrent]
          }, {
            name: '取消条数',
            type: 'bar',
            data: [data[0].cancelTotal,
              data[0].cancelTotalCurrent]
          }, {
            name: '新增条数',
            type: 'bar',
            data: [data[0].newTotal,
              data[0].newTotalCurrent]
          },]
        });

      }



      //methods end
    },
  }
</script>

<style scoped>
  .demo-split {
    height: 40em;
    border: 1px solid #dcdee2;
    text-align: center;
    vertical-align: middle;
  }

  .demo-split-pane {
    padding: 10px;
  }

  .new-detail-style {
    background-color: #2db7f5;
    color: #fff;
  }

  .old-detail-style {
    background-color: #2db7f5;
    color: #ff6600;
  }


</style>
